import { createClient } from '@supabase/supabase-js';
import { config } from '../config';

const supabaseUrl = config.supabaseUrl;
const supabaseKey = config.supabaseKey;

const supabase = createClient(supabaseUrl, supabaseKey);

export interface ScheduledTask {
  id: string;
  created_at: string;
  name: string;
  task_type: 'reminder' | 'notification' | 'data_sync';
  status: 'active' | 'paused' | 'completed';
  next_run: string;
  cron_expression: string;
  parameters?: Record<string, any>;
}

export const scheduleService = {
  findAll: async () => {
    const { data, error } = await supabase
      .from('scheduled_tasks')
      .select('*')
      .order('created_at', { ascending: false });
      
    if (error) throw new Error(error.message || '请求失败');
    return data as ScheduledTask[];
  },
  
  findById: async (column: string, value: string) => {
    const { data, error } = await supabase
      .from('scheduled_tasks')
      .select('*')
      .eq(column, value)
      .single();
      
    if (error) throw new Error(error.message || '请求失败');
    return data as ScheduledTask;
  },
  
  create: async (data: Partial<ScheduledTask>) => {
    const { data: result, error } = await supabase
      .from('scheduled_tasks')
      .insert(data)
      .select()
      .single();
      
    if (error) throw new Error(error.message || '创建失败');
    return result as ScheduledTask;
  },
  
  update: async (id: string, data: Partial<ScheduledTask>) => {
    const { data: result, error } = await supabase
      .from('scheduled_tasks')
      .update(data)
      .eq('id', id)
      .single();
      
    if (error) throw new Error(error.message || '更新失败');
    return result as ScheduledTask;
  },
  
  delete: async (id: string) => {
    const { error } = await supabase
      .from('scheduled_tasks')
      .delete()
      .eq('id', id);
      
    if (error) throw new Error(error.message || '删除失败');
    return true;
  },
  
  // 自定义按状态查询方法
  findByStatus: async (status: ScheduledTask['status']) => {
    const { data, error } = await supabase
      .from('scheduled_tasks')
      .select('*')
      .eq('status', status)
      .order('created_at', { ascending: false });
      
    if (error) throw new Error(error.message || '请求失败');
    return data as ScheduledTask[];
  }
}; 